package com.itestmini.testplatformbackend.common;

import com.itestmini.testplatformbackend.dto.ResultDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author moso
 * @Date 2024/12/23 23:35
 * 该类需要能捕获 1.业务异常
 * 2. 非业务异常
 * 3. 其他异常
 */


@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    //业务异常
    @ExceptionHandler({ServiceException.class})
    public ResultDto serviceExceptionHandler(ServiceException se){
        return resultFormat(se);
    }

    //非业务异常
    @ExceptionHandler({Exception.class})
    public ResultDto exception(Exception e){
        return resultFormat(e);
    }

    @ExceptionHandler({Throwable.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultDto exception(Throwable throwable){
        return resultFormat(throwable);
    }


    public ResultDto resultFormat(Throwable t){
        log.error(t.getMessage());
        String tips = "系统繁忙，请稍后再试";
        if (t instanceof ServiceException){
            return ResultDto.fail("业务异常 " + tips);
        }
        if(t instanceof Exception){
            return ResultDto.fail("非业务异常 " + tips);
        }
        return ResultDto.fail(tips);
    }

}
